#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include "InetAddr.hpp"

class Command
{
public:
    Command()
    {
        SafeCommandLoad();
    }

    std::string Excute(std::string cmd_str)
    {
        FILE *fp = popen(cmd_str.c_str(), "r");
        if (fp)
        {
            std::string result;
            char line[1024];
            while (std::fgets(line, sizeof(line), fp))
            {
                result += line;
            }
            pclose(fp);
            return result.empty() ? "success" : result;
            // return result.empty() ? "success\n[END]" : result + "[END]";

        }
        return "excute error";
    }

    void Service(int sockfd, InetAddr addr)
    {
        while (true)
        {
            char buffer[1024]; // command buffer
            ssize_t n = ::recv(sockfd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string result = Excute(buffer);
                send(sockfd, result.c_str(), result.size(), 0);
            }
            else if (n == 0)
            {
                std::cout << "client quit: " << addr.Info() << std::endl;
                break;
            }
            else
            {
                std::cout << "read error " << addr.Info() << std::endl;
                break;
            }
        }
    }

private:
    void SafeCommandLoad()
    {
        std::fstream file("command.txt");
        if (!file)
        {
            perror("fstream");
        }
        std::string line;

        while (std::getline(file, line))
        {
            if (line.empty())
                continue;
            else
                _cmd_str.insert(line);
        }

        file.close();
    }

private:
    std::set<std::string> _cmd_str;
};